package ui {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.utils.setTimeout;
	import no.doomsday.console.ConsoleUtil;
	public class Input extends Sprite {
		public var id:String;
		public var title:String;
		
		private var titleTxt:TextField = new TextField();
		
		private var input:TextField = new TextField();
		public function Input(id:String, title:String, x:Number = NaN, y:Number = NaN) {
			this.id = id;
			this.title = title;
			if (!isNaN(x)) this.x = x;
			if (!isNaN(y)) this.y = y;
			
			titleTxt.defaultTextFormat = new TextFormat("Arial", 15, 0xB1B1B1);
			titleTxt.autoSize = TextFieldAutoSize.LEFT;
			titleTxt.text = title;
			addChild(titleTxt);
			
			input.defaultTextFormat = new TextFormat("Arial", 13);
			//input.x = 10;
			input.y = titleTxt.height+3;
			input.width = 300;
			input.height = 100;
			input.type = TextFieldType.INPUT;
			input.border = true;
			input.borderColor = 0xB1B1B1;
			input.background = true;
			input.multiline = true;
			input.addEventListener(Event.CHANGE, refreshOverlay);
			input.addEventListener(FocusEvent.FOCUS_IN, refreshOverlayDelayed);
			input.addEventListener(MouseEvent.MOUSE_DOWN, refreshOverlayDelayed);
			input.addEventListener(KeyboardEvent.KEY_DOWN, refreshOverlayDelayed);
			addChild(input);
			
		}
		
		public function focus():void {
			stage.focus = input;
		}
		
		public function getLines():Vector.<String> {
			if (input.length == 0) return new Vector.<String>();
			var lines:Vector.<String> = new Vector.<String>(input.numLines);
			for (var i:int = 0; i < input.numLines; i++) {
				lines[i] = input.getLineText(i);
			}
			return lines;
		}
		
		private function refreshOverlayDelayed(e:Event):void {
			addEventListener(Event.ENTER_FRAME, refreshOverlay, false, 0, true);
		}
		private function refreshOverlay(e:Event = null):void {
			removeEventListener(Event.ENTER_FRAME, refreshOverlay);
			
			var index:int = input.caretIndex;
			var lineIndex:int = index == input.length ? input.numLines-1 : input.getLineIndexOfChar(index);
			
			var line:String = lineIndex == -1 ? " " : input.getLineText(lineIndex);
			
			dispatchEvent(new TextEvent(TextEvent.TEXT_INPUT, false, false, line));
		}
		
	}

}